package mysql

import (
	"time"

	gmysql "gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Config struct {
	Dsn          string `yaml:"dsn"`
	Debug        bool   `yaml:"debug"`
	MaxIdleConns int    `yaml:"max_idle_conns"`
	MaxOpenConns int    `yaml:"max_open_conns"`
	MaxLifeTime  int    `yaml:"max_life_time"`
}

func NewDB(cfg Config, driver ...string) (*gorm.DB, error) {
	// dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(gmysql.Open(cfg.Dsn), &gorm.Config{})

	if err != nil {
		return nil, err
	}

	// 开启调试模式
	if cfg.Debug {
		db.Debug()
	}

	sqlDB, err := db.DB()

	if err != nil {
		return nil, err
	}

	// 链接池配置
	sqlDB.SetMaxIdleConns(cfg.MaxIdleConns)
	sqlDB.SetMaxOpenConns(cfg.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Duration(cfg.MaxLifeTime) * time.Second)

	return db, nil
}
